﻿using LitJson;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;

public class ShipsManager
{
    public string ConfigPath;
    public static ShipsManager Instance = new ShipsManager();
    List<Ship> m_PrefabShips = new List<Ship>();
    int m_ShipNumberIndex=0;
    GameObject m_ShipsManager;

    public Ship m_ShipPrefab;
    public ShipsManager()
    {
        ConfigPath = Utils.GetDataPath() + "ShipsList.data";
    }
    public void Init()
    {
    }
    public void AddPrefabShip(Ship ship)
    {
        var foundShip = FindPrefabShip(ship.m_ShipTypeID);
        if (foundShip != null)
            return;

        ship.m_ShipTypeID = ++m_ShipNumberIndex;
        ship.gameObject.transform.SetParent(m_ShipsManager.transform);
        ship.gameObject.name = ship.m_TypeName + "_Prefab";
        m_PrefabShips.Add(ship);
    }
    public void RemovePrefabShip(Ship ship)
    {
        var foundShip = FindPrefabShip(ship.m_ShipTypeID);
        if (foundShip == null)
            return;
        m_PrefabShips.Remove(ship);
        ship.gameObject.transform.SetParent(null);

    }

    public Ship FindPrefabShip(int shipTypeID)
    {
        foreach(var i in m_PrefabShips)
        {
            if(i.m_ShipTypeID == shipTypeID)
            {
                return i;
            }
        }
        return null;
    }
    public int GetNumberOfPrefabShips()
    {
        return m_PrefabShips.Count;
    }
    public Ship GetPrefabShip(int index)
    {
        return m_PrefabShips[index];
    }

    public void InitSystem()
    {
        m_ShipsManager = new GameObject();
        m_ShipsManager.name = "ShipsManager";
        GameObject.DontDestroyOnLoad(m_ShipsManager);
        ShipUIManager.Instance.Load();

        JsonData jsonData = Utils.LoadJson(ConfigPath);
        if (jsonData == null)
            return;
        Load(jsonData);
    }

    //  加载系统配置文件
    void Load(JsonData json)
    {
        IDictionary<string, JsonData> jsond = json.ValueAsObject();

        if (jsond.ContainsKey("ShipIndex"))
            m_ShipNumberIndex = jsond["ShipIndex"].ValueAsInt();
        m_PrefabShips.Clear();
        if (jsond.ContainsKey("Ships"))
        {
            for(int i=0; i<jsond["Ships"].Count; ++i)
            {
                var ship = GameObject.Instantiate(m_ShipPrefab);
                ship.LoadPrefab(jsond["Ships"][i]);
                ship.gameObject.name = ship.m_TypeName + "_Prefab";
                ship.gameObject.transform.SetParent(m_ShipsManager.transform);
                m_PrefabShips.Add(ship);
                ship.gameObject.SetActive(false);
            }
        }
    }

    //  加载飞船（玩家对飞船的表层配置信息）
    public Ship LoadShip(JsonData json)
    {
        IDictionary<string, JsonData> jsond = json.ValueAsObject();
        int typeID = -1;
        if (jsond.ContainsKey("TypeID"))
            typeID = jsond["TypeID"].ValueAsInt();
        if (typeID == -1)
        {
            MessageShow.Instance.Warning("加载舰船失败！没看到舰船的出厂编号。可能是一艘非法船只。");
            return null;
        }
        var newShip= FindPrefabShip(typeID);
        if(!newShip)
        {
            MessageShow.Instance.Warning("加载舰船失败！错误的舰船的出厂编号。可能是一艘非法船只。");
            return null;
        }
        var ship = GameObject.Instantiate(newShip);
        ship.LoadPrefab(newShip.jsonData);
        ship.Load(json);
        ship.gameObject.SetActive(false);
        ship.gameObject.name = ship.m_TypeName+"_Loaded";
        return ship;
    }
    public void Save()
    {
        JsonData root = new JsonData();

        root["ShipIndex"] = m_ShipNumberIndex;

        root["Ships"] = new JsonData();
        root["Ships"].SetJsonType(JsonType.Array);

        for (int j = 0; j < m_PrefabShips.Count; ++j)
        {
            root["Ships"].Add(m_PrefabShips[j].SavePrefab());
        }

        string data = root.ToJson();
        using (FileStream fs = new FileStream(ConfigPath, FileMode.Create, FileAccess.Write))
        {
            byte[] array = System.Text.Encoding.UTF8.GetBytes(data);
            fs.Write(array, 0, (int)array.Length);
            fs.Close();
        }
    }
}